package net.maku.kyy.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import net.maku.framework.common.constant.Constant;
import net.maku.framework.common.constant.MessageConstant;
import net.maku.framework.common.exception.ServerException;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import net.maku.framework.security.utils.ThreadLocalUtil;
import net.maku.kyy.constant.KyyConstant;
import net.maku.kyy.constant.KyyRedisKeyConstant;
import net.maku.kyy.convert.KyyForumConvert;
import net.maku.kyy.dao.KyyUserDao;
import net.maku.kyy.entity.KyyForumEntity;
import net.maku.kyy.query.KyyForumQuery;
import net.maku.kyy.utils.GetUserMessageUtil;
import net.maku.kyy.vo.KyyForumVO;
import net.maku.kyy.dao.KyyForumDao;
import net.maku.kyy.service.KyyForumService;
import com.fhs.trans.service.impl.TransService;
import net.maku.framework.common.utils.ExcelUtils;
import net.maku.kyy.vo.KyyForumExcelVO;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 圈子表
 *
 * @author MAKU babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@Service
@AllArgsConstructor
public class KyyForumServiceImpl extends BaseServiceImpl<KyyForumDao, KyyForumEntity> implements KyyForumService {
    private final TransService transService;
    @Autowired
    private KyyUserDao kyyUserDao;
    @Autowired
    private KyyForumDao kyyForumDao;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @Override
    public PageResult<KyyForumVO> page(KyyForumQuery query) {
        IPage<KyyForumEntity> page = baseMapper.selectPage(getPage(query), getWrapper(query));
        return new PageResult<>(KyyForumConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }


    private LambdaQueryWrapper<KyyForumEntity> getWrapper(KyyForumQuery query){
        LambdaQueryWrapper<KyyForumEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ObjectUtil.isNotEmpty(query.getHead()), KyyForumEntity::getHead, query.getHead());

        wrapper.like(ObjectUtil.isNotEmpty(query.getName()), KyyForumEntity::getName, query.getName());

        wrapper.like(ObjectUtil.isNotEmpty(query.getGamename()), KyyForumEntity::getGamename, query.getGamename());

        wrapper.like(ObjectUtil.isNotEmpty(query.getTitle()), KyyForumEntity::getTitle, query.getTitle());

        wrapper.like(ObjectUtil.isNotEmpty(query.getContent()), KyyForumEntity::getContent, query.getContent());

        wrapper.eq(ObjectUtil.isNotEmpty(query.getImage()), KyyForumEntity::getImage, query.getImage());

        wrapper.eq(ObjectUtil.isNotEmpty(query.getTag1()), KyyForumEntity::getTag1, query.getTag1());

        wrapper.eq(ObjectUtil.isNotEmpty(query.getTag2()), KyyForumEntity::getTag2, query.getTag2());

        wrapper.eq(ObjectUtil.isNotEmpty(query.getTag3()), KyyForumEntity::getTag3, query.getTag3());

        wrapper.eq(ObjectUtil.isNotEmpty(query.getType()), KyyForumEntity::getType, query.getType());

        wrapper.eq(ObjectUtil.isNotEmpty(query.getNum1()), KyyForumEntity::getNum1, query.getNum1());

        wrapper.eq(ObjectUtil.isNotEmpty(query.getNum2()), KyyForumEntity::getNum2, query.getNum2());

        wrapper.eq(ObjectUtil.isNotEmpty(query.getNum3()), KyyForumEntity::getNum3, query.getNum3());

        wrapper.eq(ObjectUtil.isNotEmpty(query.getOpenid()), KyyForumEntity::getOpenid, query.getOpenid());

        //打乱顺序，猜你喜欢
        if ("true".equals(query.getRandomGame())) {
            wrapper.last("ORDER BY RAND()");
        }
        //最热
        wrapper.orderByDesc(ObjectUtil.isNotEmpty(query.getIsHot()) &&"true".equals(query.getIsHot()), KyyForumEntity::getNum1);
        //最新
        wrapper.orderByDesc(ObjectUtil.isNotEmpty(query.getIsCurrent()) &&"true".equals(query.getIsCurrent()), KyyForumEntity::getCreateTime);
        //有图
        if ("true".equals(query.getHasImage())) {
            wrapper.isNotNull(KyyForumEntity::getImage);
            wrapper.ne(KyyForumEntity::getImage, "");
        }
        //没图
        if ("true".equals(query.getNullImage())) {
            wrapper.isNull(KyyForumEntity::getImage).or().eq(KyyForumEntity::getImage, "");
        }
        return wrapper;
    }


    @Override
    public KyyForumVO get(Long id) {
        KyyForumEntity entity = baseMapper.selectById(id);
        KyyForumVO vo = KyyForumConvert.INSTANCE.convert(entity);
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(KyyForumVO vo) {
//        Long userId = Long.valueOf(vo.getCreator());
//        Map map=ThreadLocalUtil.get();
//        Long userLoginId = (Long) map.get(KyyConstant.KYY_USER_ID);
//        if (userId != userLoginId){
//            throw new ServerException(MessageConstant.PLEASE_LOGIN);
//        }
//        Long forumPermission=kyyUserDao.selectForumPermissionById(userId);
//        if (forumPermission== Long.valueOf(Constant.DISABLE)){
//            throw new ServerException(MessageConstant.FORUM_PERMISSION_DISABLE);
//        }
        KyyForumEntity entity = KyyForumConvert.INSTANCE.convert(vo);
        baseMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(KyyForumVO vo) {
        KyyForumEntity entity = KyyForumConvert.INSTANCE.convert(vo);

        updateById(entity);


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);

    }



    @Override
    public void export() {
    List<KyyForumExcelVO> excelList = KyyForumConvert.INSTANCE.convertExcelList(list());
        transService.transBatch(excelList);
        ExcelUtils.excelExport(KyyForumExcelVO.class, "圈子表", null, excelList);
    }

    /**
     * 获取个人帖子
     * @return
     */
    @Override
    public PageResult<KyyForumVO> pageForumMe(@ParameterObject @Valid KyyForumQuery query) {
        Map map=ThreadLocalUtil.get();
        if (map==null){
            throw new ServerException(MessageConstant.PLEASE_LOGIN);
        }
        Long userId = (Long) map.get(KyyConstant.KYY_USER_ID);
        IPage<KyyForumEntity> page = baseMapper.selectPageByUserId(getPage(query), userId, query);
        return new PageResult<>(KyyForumConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }

    /**
     * 更新评论量+1
     */
    public void updateNum2(Integer id) {
        kyyForumDao.updateNum2Add(id);
    }

    /**
     * 更新浏览量
     */
    public void updateNum1(Integer id) {
        kyyForumDao.updateNum1Add(id);
    }

    /**
     * 更新点赞量
     */
    @Transactional
    @Override
    public void updateNum3(Integer id) {
        Long userId = GetUserMessageUtil.getUserId();
        String key= KyyRedisKeyConstant.KYY_FORUM_LIKE+":"+id;
        if (isExitGood(userId,key)){
            //存在点赞,则点赞数减一
            kyyForumDao.updateNum3Reduce(id);
            //删除set集合中的相关数据
            redisTemplate.opsForSet().remove(key,userId.toString());
            return;
        }
        //不存在点赞，则点赞数加一
        kyyForumDao.updateNum3Add(id);
        redisTemplate.opsForSet().add(key, String.valueOf(userId));
    }

    /**
     * 更新点赞量-1
     * @param id
     */
    @Transactional
    @Override
    public void updateNum3Reduce(Integer id) {
        kyyForumDao.updateNum3Reduce(id);
    }

    /**
     * 判断用户是否已点赞
     * @param forumId
     * @return true 已点赞 false 未点赞
     */
    @Override
    public Boolean getLikeStyle(Long forumId) {
        Long userId = GetUserMessageUtil.getUserId();
        String key= KyyRedisKeyConstant.KYY_FORUM_LIKE+":"+forumId;
        return isExitGood(userId,key);
    }


    /**
     * 判断待用户是否已点赞
     * @param userId 用户id
     * @param key 查询的帖子key
     * @return true 已点赞 false 未点赞
     */
    public boolean isExitGood(Long userId,String key){
        //判断表是否存在
        if (!redisTemplate.hasKey(key)){
            //创建redis中的set集合
            return false;
        }
        //查询key是否存在
        if (redisTemplate.opsForSet().isMember(key,userId.toString())){
            //存在
            return true;
        }
        return false;
    }
}